package cn.wolfcode.trip.base.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {
    @Autowired
    private IUserService userService;

    /**
     * 登陆
     * @param email
     * @param password
     * @return
     */
    @PostMapping
    public Object login(@RequestParam String email, @RequestParam String password){
        JSONResult result = new JSONResult();
        try {
            // 调用业务方法登陆操作
            User u = userService.login(email, password);
            // 登陆成功，存入session
            UserContext.setCurrentUser(u);
            // 设置到JSONResult，然后转成JSON格式
            result.setData(u);
        } catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }


    /**
     * 注销
     * @param session
     * @param response
     */
    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse response){
        // 销毁session
        session.invalidate();
        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
